package game.network;
import game.Model;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class ClientThread implements Runnable {

	private Model model;
	private String host;

	public ClientThread(Model network, String host) {
		this.model = network;
		this.host = host;
	}

	public void run() {
		Socket serverSocket = null;
		OutputStream os = null;
		ObjectOutputStream oos = null;
		InputStream is = null;
		ObjectInputStream ois = null;
		try {
			serverSocket = new Socket(host, 4444);
			serverSocket.setTcpNoDelay(true);
			os = serverSocket.getOutputStream();
			oos = new ObjectOutputStream(os);
			is = serverSocket.getInputStream();
			ois = new ObjectInputStream(is);
			while (model.isNetworkWorking()) {
				
				sendPacket(oos, model.getPacket());
				
				Packet packetSet = receivePacket(ois);
				
				model.setPacket(packetSet);
								
				Thread.sleep(10);
			}
			serverSocket.close();
			os.close();
			oos.close();
			is.close();
			ois.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Packet receivePacket(ObjectInputStream ois) throws IOException {
		int playerX = ois.readInt();
		int playerY = ois.readInt();
		int playerLife = ois.readInt();
		int numberBullets = ois.readInt();
		List<Integer> bulletX = new ArrayList<Integer>();
		List<Integer> bulletY = new ArrayList<Integer>();
		
		for (int i=0; i<numberBullets; i++){
			bulletX.add(ois.readInt());
			bulletY.add(ois.readInt());
		}
		
		Packet packetSet = new Packet(playerX, playerY, playerLife, bulletX, bulletY);
		return packetSet;
	}

	public static void sendPacket(ObjectOutputStream oos, Packet packet) throws IOException {		
		oos.writeInt(packet.getPlayerX());
		oos.writeInt(packet.getPlayerY());
		oos.writeInt(packet.getPlayerLife());
		oos.writeInt(packet.getBulletX().size());
		for (int i=0; i<packet.getBulletX().size(); i++){
			oos.writeInt(packet.getBulletX().get(i));
			oos.writeInt(packet.getBulletY().get(i));
		}
								
		oos.flush();
	}
}
